import React, {useEffect, useState} from 'react';
import {Badge, Button, Col, Divider, Form, Input, message, Modal, Popconfirm, Row, Spin, Table} from 'antd';
import type {ColumnsType} from 'antd/es/table';
import {
  addInterfaceInfoUsingPOST,
  deleteInterfaceInfoByIdUsingDELETE,
  offlineUsingPUT,
  onlineUsingPUT,
  paginationQueryUsingGET, updateInterfaceInfoUsingPOST
} from "@/services/lapi-backend/interfaceinfoAdmin";
import dayjs from 'dayjs'
import TextArea from "antd/es/input/TextArea";
import Search from "antd/es/input/Search";
import {QuestionCircleOutlined} from "@ant-design/icons";
import JSONView, {InteractionProps} from "react-json-view";

const App: React.FC = () => {
  const [InterfaceInfoData, setInterfaceInfoData] = useState<API.InterfaceInfo[]>([]);
  const [detailInterface, setDetailInterface] = useState<API.InterfaceInfo>({});
  const [total, setTotal] = useState<number>(0);
  const [pageNow, setPageNow] = useState<number>(1);
  const [loading, setLoading] = useState<boolean>(false);
  const [addLoading, setAddLoading] = useState<boolean>(false);
  const [modalOpen, setModalOpen] = useState<boolean>(false);
  const [addModalOpen, setAddModalOpen] = useState<boolean>(false);
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);
  const [interfaceUpdate, setInterfaceUpdate] = useState<API.InterfaceInfoUpdateRequest>({})
  const [interfaceAdd, setInterfaceAdd] = useState<API.InterfaceInfoAddRequest>({})
  const [pageParam, setPageParam] = useState<API.paginationQueryUsingGETParams>({})
  const [jsonData, setJsonData] = useState({})
  const [addData, setAddData] = useState({})
  const online = (id: number, index: number) => {
    onlineUsingPUT({id}, {}).then(r => {
      if (r.code == 0) {
        const newData: API.InterfaceInfo[] = [];
        InterfaceInfoData.forEach((item, ind) => {
          newData[ind] = item;
        })
        newData[index].status = 1;
        setInterfaceInfoData(newData);
        message.success(r.message);
      } else {
        message.error(r.message);
      }
    })
  }

  const offline = (id: number, index: number) => {
    offlineUsingPUT({id}, {}).then(r => {
      if (r.code == 0) {
        const newData: API.InterfaceInfo[] = [];
        InterfaceInfoData.forEach((item, ind) => {
          newData[ind] = item;
        })
        newData[index].status = 0;
        setInterfaceInfoData(newData);
        message.success(r.message);
      } else {
        message.error(r.message);
      }
    })
  }
  const handleChange = (e: InteractionProps) => {
    setJsonData(e.updated_src);
  }
  const handleAddChange = (e: InteractionProps) => {
    setAddData(e.updated_src);
  }
  const pageQuery = (page: number) => {
    setLoading(true)
    pageParam.pageNow = page

    paginationQueryUsingGET(pageParam, {}).then(res => {
      const pageInterfaceVo = res.data;
      if (pageInterfaceVo == null || pageInterfaceVo.data == null)
        return;
      setTotal(pageInterfaceVo?.total as number)
      for (let i = 0; i < pageInterfaceVo.data.length!; i++) {
        if (pageInterfaceVo.data != null) {
          const createTime = pageInterfaceVo.data[i].createTime;
          const updateTime = pageInterfaceVo.data[i].updateTime;
          pageInterfaceVo.data[i].createTime = dayjs(createTime).format('YYYY-MM-DD');
          pageInterfaceVo.data[i].updateTime = dayjs(updateTime).format('YYYY-MM-DD');
        }
      }
      setInterfaceInfoData(pageInterfaceVo?.data as API.InterfaceInfo[])
      setLoading(false)
    })
  }
  const deleteInterface = (id: number) => {
    deleteInterfaceInfoByIdUsingDELETE({id}, {}).then(r => {
      if (r.code == 0) {
        message.success("删除成功");
        pageQuery(pageNow)
      } else {
        message.error(r.message)
      }
    })
  }
  const columns: ColumnsType<API.InterfaceInfo> = [
    {
      title: '名称',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '请求方法',
      align: 'center',
      dataIndex: 'method',
    },
    {
      title: '请求路径',
      align: 'center',
      dataIndex: 'path',
    },
    {
      title: '接口状态',
      align: 'center',
      dataIndex: 'status',
      render: (status: number) => {
        if (status === 0) {
          return <Badge status="error" text={'关闭'}/>
        } else {
          return <Badge status="success" text={'开启'}/>
        }
      }
    },
    {
      title: '接口描述',
      align: 'center',
      dataIndex: 'description',
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',

    },
    {
      title: '更新时间',
      align: 'center',
      dataIndex: 'createTime',
    },
    {
      title: "操作",
      dataIndex: "status",
      align: 'center',
      width: '450px',
      render: (r, interfaceInfo, index) => {
        return <div>
          <Button
            onClick={() => {
              online(interfaceInfo.id as number, index)
            }}
            type="link" disabled={r == 1}>上线</Button>
          <Divider type={"vertical"}/>
          <Button
            onClick={() => {
              offline(interfaceInfo.id as number, index)
            }}
            type="link" disabled={r == 0}>下线 </Button>
          <Divider type={"vertical"}/>
          <Button
            onClick={() => {
              setDetailInterface(interfaceInfo)
              setModalOpen(true)
            }}
            type="link">详细</Button>
          <Divider type={"vertical"}/>
          <Button
            onClick={() => {
              setJsonData(JSON.parse(interfaceInfo.requestParam == undefined ? "{}" : interfaceInfo.requestParam))

              setDetailInterface(interfaceInfo)
              setInterfaceUpdate(interfaceInfo)
              setUpdateModalOpen(true)
            }}
            type="link">修改</Button> <Divider type={"vertical"}/>
          <Popconfirm
            title="你确定删除接口吗？"
            onCancel={() => {
              //
            }}
            onConfirm={() => {
              deleteInterface(interfaceInfo.id == undefined ? 0 : interfaceInfo.id)
            }}
            icon={<QuestionCircleOutlined style={{color: 'red'}}/>}
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        </div>

      }
    }
  ];
  useEffect(() => {
    setLoading(true)
    paginationQueryUsingGET({pageNow: 1, pageSize: 10}, {}).then(res => {
      const pageInterfaceVo = res.data;
      if (pageInterfaceVo == null || pageInterfaceVo.data == null)
        return;
      setTotal(pageInterfaceVo?.total as number)
      for (let i = 0; i < pageInterfaceVo.data.length!; i++) {
        if (pageInterfaceVo.data != null) {
          const createTime = pageInterfaceVo.data[i].createTime;
          const updateTime = pageInterfaceVo.data[i].updateTime;
          pageInterfaceVo.data[i].createTime = dayjs(createTime).format('YYYY-MM-DD');
          pageInterfaceVo.data[i].updateTime = dayjs(updateTime).format('YYYY-MM-DD');
        }
      }
      setInterfaceInfoData(pageInterfaceVo?.data as API.InterfaceInfo[])
      setLoading(false)
    })
  }, [])
  const updateInterface = () => {
    interfaceUpdate.requestParam = JSON.stringify(jsonData);
    updateInterfaceInfoUsingPOST(interfaceUpdate, {}).then(r => {
      if (r.code === 0) {
        setUpdateModalOpen(false);
        pageQuery(pageNow)
        message.success(r.message)
      } else {
        message.error(r.message);
      }
    })
  }
  const addInterface = () => {
    interfaceAdd.requestParam = JSON.stringify(addData);
    setLoading(true)
    addInterfaceInfoUsingPOST(interfaceAdd, {}).then(r => {
      setLoading(false)
      if (r.code === 0) {
        setAddModalOpen(false)
        setInterfaceAdd({})
        pageQuery(pageNow)
        message.success(r.message)
      } else {
        message.error(r.message);
      }

    })
  }
  return (
    <div>
      <Row justify="space-between" align="bottom">
        <Col span={8} offset={8}> <Search placeholder="输入接口名搜索" enterButton onSearch={e => {
          setPageNow(1)
          pageParam.name = e;
          pageParam.pageSize = 10
          pageQuery(1)
        }}/></Col>
        <Col span={8} flex="0  100px"> <Button type="primary" onClick={() => {
          setAddModalOpen(true)
        }}>新增接口</Button></Col>
      </Row>
      <Divider plain></Divider>
      <Table
        loading={loading}
        rowSelection={{
          type: 'checkbox',
        }}
        columns={columns}
        pagination={
          {
            showTotal: (total, range) => {
              return "总记录条数:" + total + "条"
            },
            showQuickJumper: true,
            pageSize: 10,

            total: total,
            position: ["bottomCenter"],
            onChange: (page) => {

              setPageNow(page)
              pageQuery(page)
            }
          }
        }
        dataSource={InterfaceInfoData}
      />

      <Modal
        title={detailInterface.name + "  详情页"}
        centered
        open={modalOpen}
        onOk={() => setModalOpen(false)}
        onCancel={() => setModalOpen(false)}
      >
        {Object.keys(detailInterface).map(r => {
          return <p> {r} : {detailInterface[r]}</p>
        })}
      </Modal>
      <Modal
        title={"修改接口 " + detailInterface.name}
        centered
        destroyOnClose
        open={updateModalOpen}
        onOk={() => {
          updateInterface()
        }}
        onCancel={() => setUpdateModalOpen(false)}
        maskClosable={false}
      >
        <Form
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="name"
            rules={[{required: true, message: 'Please input the title of collection!'}]}
          >
            <Input defaultValue={detailInterface.name} onChange={(e) => {
              interfaceUpdate.name = e.target.value;
              setInterfaceUpdate(interfaceUpdate);
            }}/>
          </Form.Item>
          <Form.Item
            name="url"
            label="url"
            rules={[{required: true, message: 'Please input the title of collection!'}]}
          >
            <Input defaultValue={detailInterface.url} onChange={(e) => {
              interfaceUpdate.url = e.target.value;
              setInterfaceUpdate(interfaceUpdate);
            }}/>
          </Form.Item> <Form.Item
          name="method"
          label="method"
          rules={[{required: true, message: 'Please input the title of collection!'}]}
        >
          <Input defaultValue={detailInterface.method} onChange={(e) => {
            interfaceUpdate.method = e.target.value;
            setInterfaceUpdate(interfaceUpdate);
          }}/>
        </Form.Item>
          <Form.Item
            name="requestParam"
            label="requestParam"
            rules={[{required: true, message: 'Please input the title of collection!'}]}
          >
            <div></div>
            <JSONView src={(jsonData)}
                      displayDataTypes={false}
                      name={false}
                      displayObjectSize={false}
                      enableClipboard={false}
                      onEdit={(edit) => {
                        handleChange(edit)
                      }}
                      onAdd={add => {
                        handleChange(add)
                      }}
                      onDelete={(del) => {

                        handleChange(del)
                      }}
                      theme={"ocean"}/>

          </Form.Item> <Form.Item
          name="requestHeader"
          label="requestHeader"
          rules={[{required: true, message: 'Please input the title of collection!'}]}
        >
          <TextArea defaultValue={detailInterface.requestHeader} onChange={(e) => {
            interfaceUpdate.requestHeader = e.target.value;
            setInterfaceUpdate(interfaceUpdate);
          }}/>
        </Form.Item>
          <Form.Item
            name="responseHeader"
            label="responseHeader"
            rules={[{required: true, message: 'Please input the title of collection!'}]}
          >
            <TextArea defaultValue={detailInterface.responseHeader} onChange={(e) => {
              interfaceUpdate.responseHeader = e.target.value;
              setInterfaceUpdate(interfaceUpdate);
            }}/>
          </Form.Item>
          <Form.Item
            name="path"
            label="path"
            rules={[{required: true, message: 'Please input the title of collection!'}]}
          >
            <Input defaultValue={detailInterface.path} onChange={(e) => {
              interfaceUpdate.path = e.target.value;
              setInterfaceUpdate(interfaceUpdate);
            }}/>
          </Form.Item>
          <Form.Item name="description" label="Description">
            <TextArea defaultValue={detailInterface.description} onChange={(e) => {
              interfaceUpdate.description = e.target.value;
              setInterfaceUpdate(interfaceUpdate);

            }}/>

          </Form.Item>

        </Form>
      </Modal>


      <Modal
        title={"新增接口信息 "}
        centered
        destroyOnClose
        open={addModalOpen}
        onOk={() => {
          addInterface()
        }}
        onCancel={() => setAddModalOpen(false)}
        maskClosable={false}
      >
        <Spin spinning={addLoading}>
          <Form
            layout="vertical"
          >
            <Form.Item
              name="name"
              label="name"
              rules={[{required: true, message: 'Please input the title of collection!'}]}
            >
              <Input defaultValue={interfaceAdd.name} onChange={(e) => {
                interfaceAdd.name = e.target.value;
                setInterfaceAdd({...interfaceAdd})
              }}/>
            </Form.Item>
            <Form.Item
              name="url"
              label="host"
              rules={[{required: true, message: 'Please input the title of collection!'}]}
            >
              <Input defaultValue={interfaceAdd.url} onChange={(e) => {
                interfaceAdd.url = e.target.value;
                setInterfaceAdd({...interfaceAdd})
              }}/>
            </Form.Item> <Form.Item
            name="method"
            label="method"
            rules={[{required: true, message: 'Please input the title of collection!'}]}
          >
            <Input defaultValue={interfaceAdd.method} onChange={(e) => {
              interfaceAdd.method = e.target.value;
              setInterfaceAdd({...interfaceAdd})
            }}/>
          </Form.Item>
            <Form.Item
              name="requestParam"
              label="requestParam"
              rules={[{required: true, message: 'Please input the title of collection!'}]}
            >
              <div></div>
              <JSONView src={addData}
                        displayDataTypes={false}
                        name={false}
                        displayObjectSize={false}
                        enableClipboard={false}
                        onEdit={(edit) => {
                          handleAddChange(edit)
                        }}
                        onAdd={add => {
                          handleAddChange(add)
                        }}
                        onDelete={(del) => {
                          handleAddChange(del)
                        }}
                        theme={"ocean"}/>

            </Form.Item> <Form.Item
            name="requestHeader"
            label="requestHeader"
            rules={[{required: true, message: 'Please input the title of collection!'}]}
          >
            <TextArea defaultValue={interfaceAdd.requestHeader} onChange={(e) => {
              interfaceAdd.requestHeader = e.target.value;
              setInterfaceAdd({...interfaceAdd})
            }}/>
          </Form.Item>
            <Form.Item
              name="responseHeader"
              label="responseHeader"
              rules={[{required: true, message: 'Please input the title of collection!'}]}
            >
              <TextArea defaultValue={interfaceAdd.requestHeader} onChange={(e) => {
                interfaceAdd.responseHeader = e.target.value;
                setInterfaceAdd({...interfaceAdd})
              }}/>
            </Form.Item>
            <Form.Item
              name="path"
              label="path"
              rules={[{required: true, message: 'Please input the title of collection!'}]}
            >
              <Input defaultValue={interfaceAdd.path} onChange={(e) => {
                interfaceAdd.path = e.target.value;
                setInterfaceAdd({...interfaceAdd})
              }}/>
            </Form.Item>
            <Form.Item name="description" label="Description">
              <TextArea defaultValue={interfaceAdd.description} onChange={(e) => {
                interfaceAdd.description = e.target.value;
                setInterfaceAdd({...interfaceAdd})
              }}/>
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    </div>

  );
};

export default App;
